package com.aischool.service;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import com.aischool.utils.StringUtil;
import com.jfinal.aop.Inject;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.ehcache.CacheKit;

public class SysUserRoleService {

	public final String CK_CacheName = "CacheRole";
	public final String CK_Sys_User_Role_UID_pre = "CK_Sys_User_Role_UID_";
	
	public String getCKUserAppRole(int user_id, int app_id) {
		return "CK_Sys_App_"+app_id+"_User_"+user_id+"_Role";
	}
	
	@Inject 
	SysRoleService sysRoleService;
	@Inject
	SysUserAppService sysUserAppService;
	
	/**
	 * 获取用户所属角色
	 * @param user_id
	 * @return
	 */
	public List<Record> getUserRole(int user_id){
		return Db.findByCache(CK_CacheName, CK_Sys_User_Role_UID_pre + user_id, 
				"SELECT a.* FROM sys_user_role a WHERE a.user_id = ?", 
				user_id);
	}
	
	/**
	 * 获取用户所属角色
	 * @param user_id
	 * @return
	 */
	public List<Record> getUserRole(int user_id, int app_id){
		return Db.findByCache(CK_CacheName, getCKUserAppRole(user_id, app_id), 
				"SELECT a.* FROM sys_user_role a INNER JOIN sys_role b ON b.role_id = a.role_id WHERE b.role_state = 1 AND a.user_id = ?", 
				user_id);
	}
	
	/**
	 * 更想你用户应用权限
	 * @param user_id
	 * @param request
	 * @return
	 */
	public int updateUserRole(int user_id, HttpServletRequest request) {
		int ir = 0;
		int role_id = 0;
		String result = "";
		String ids_del = "";
		List<Record> listUserApp = sysUserAppService.getUserApp(user_id);
		List<Record> listrd = sysRoleService.getSysRoleAll();
		for(int j=0;j<listUserApp.size();j++) {
			int app_id = listUserApp.get(j).getInt("app_id");
			ids_del = "";
			for(int r=0;r<listrd.size();r++) {
				role_id = listrd.get(r).getInt("role_id");
				result = request.getParameter("role_id_" + app_id + "_" + role_id);
				if (result != null && !"".equals(result)) {
					ir += Db.update("INSERT INTO sys_user_role VALUES(?, ?, ?) ON CONFLICT ON CONSTRAINT pk_sys_user_role DO NOTHING", 
							user_id, app_id, role_id);
				}else {
					ids_del += role_id + ",";
				}
			}
			
			if (ids_del.length()>0) {
				ir += Db.delete("DELETE FROM sys_user_role WHERE user_id = " + user_id + " AND app_id = " + app_id + " AND role_id IN(" + StringUtil.trim(ids_del, ',') + ")");
			}
			if (ir>0) {
				CacheKit.remove(CK_CacheName, CK_Sys_User_Role_UID_pre + user_id);
				CacheKit.remove(CK_CacheName, getCKUserAppRole(user_id, app_id));
			}
		}
		
		
		return ir;
	}
	
	
	public int setUserAppRole(int user_id, int app_id, int role_id) {
		return Db.update("INSERT INTO sys_user_role VALUES(?, ?, ?) ON CONFLICT ON CONSTRAINT pk_sys_user_role DO NOTHING", 
				user_id, app_id, role_id);
	}
	
	public void removeCache() {
		CacheKit.removeAll(CK_CacheName);
	}
}
